package com.yanyq.week02.servlet;

import com.yanyq.week02.entity.User;
import com.yanyq.week02.util.DBConnManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@WebServlet("/ConnectionServlet")
public class ConnectionServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(ConnectionServlet.class.getName());
    Statement statement = null;
    ResultSet resultSet = null;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Connection connection = DBConnManager.getConnection();
            String sql = "SELECT id, `name`, age from `user`";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            List<User> userList = new ArrayList<>();
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                userList.add(user);
            }
            // resp.getWriter().write(userList.toString());
            req.setAttribute("userList", userList);
            DBConnManager.close(connection, statement, resultSet);
            req.getRequestDispatcher("/WEB-INF/jsp/user.jsp").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
